#include <string.h>
#include <assert.h>

#include "lexical.h"

char token[200];


size_t next_char( const char* src, size_t off )
{
    char c;
    while ( c = src[off] != '\0')
    {
        switch(c)
        {
        case ' ':
        case '\n': /*skip space*/
            off++;
            break;
        case ';': /* comment line */
            do{
                c = src[++off];
            } while ( c != '\n' && c != '\0');
            break;
        default:
            return off;
        }
    }
    return 0;
}

size_t next_token( const char* src, size_t off )
{
    char c;
    for ( ; c != '\0' && 
              c != '\n' && 
              c != ' ' && 
              c != ';' && 
              c != ')'
              ; c = src[++off] );
    return off;
    
}

char* lex_ptr;
char* symbol_ptr;
char* symbol_table;

char lex_get_char()
{
    while ( *lex_ptr == ' ' || *lex_ptr == '\t' 
            || *lex_ptr == '\n' )
    {
        lex_ptr++;
    }
    return *lex_ptr;
}

void lex_skip_char()
{
    lex_ptr++;
}

char* match_symbol( char* p )
{
    while ( *p != ' ' && *p != '\t' && *p != '\n' 
            && *p != ')' && *p != '(' && *p != '\0' )
    {
        p++;
    }
    return p;
}

void lex_start( const char* text )
{
    lex_ptr = text;
    symbol_table = malloc( sizeof(char) * strlen(text) );
    symbol_ptr = symbol_table;
}

char* lex_next_token()
{
    char* p = lex_ptr;

    lex_ptr = match_symbol( p );
    
    size_t len = lex_ptr - p;
    p = memcpy( symbol_ptr, p, len );
    symbol_ptr += len;
    *symbol_ptr = '\0';
    symbol_ptr++;
    return p;

}

void lex_end()
{
    lex_ptr = 0;
    free( symbol_table );
    symbol_table = 0;
}
